package com.hope.bubble.controller;

import com.hope.bubble.common.api.ApiResult;
import com.hope.bubble.model.dto.LoginDTO;
import com.hope.bubble.model.dto.RegisterDTO;
import com.hope.bubble.model.entity.UmsUser;
import com.hope.bubble.service.IUmsUserService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.hope.bubble.jwt.JwtUtil.USER_NAME;

/**
 * 文件名：UmsUserController
 * 创建者：hope
 * 邮箱：1602774287@qq.com
 * 微信：hope4cc
 * 创建时间：2022/10/21-20:34
 * 描述：
 */
@RestController
@RequestMapping("/ums/user")
public class UmsUserController extends BaseController {
    @Resource
    private IUmsUserService iUmsUserService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    //接受客户端(前端)发送过来的的数据dto
    public ApiResult<Map<String, Object>> register(@Valid @RequestBody RegisterDTO dto) {
        //调用业务层 处理数据
        UmsUser user = iUmsUserService.executeRegister(dto);
        //如果客户端传的数据是空 返回msg 注册失败
        if (ObjectUtils.isEmpty(user)) {
            return ApiResult.failed("账号注册失败");
        }
        //将user存入 map 返回给客户端
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", user);
        return ApiResult.success(map);
    }



    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult<Map<String, String>> login(@Valid @RequestBody LoginDTO dto) {
        //先从请求体里获得 客户端 传过来 dto
        //然后调用service 层的executeLogin方法 处理
        String token = iUmsUserService.executeLogin(dto);
        //如果token为空,也就是说用一个空的用户名去生成token ,返回msg
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        //把token存到map 返回给客户端
        map.put("token", token);
        return ApiResult.success(map, "登录成功");
    }



    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ApiResult<UmsUser> getUser(@RequestHeader(value = USER_NAME) String userName) {
        UmsUser user = iUmsUserService.getUserByUsername(userName);
        return ApiResult.success(user);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResult<Object> logOut() {
        return ApiResult.success(null, "注销成功");
    }

}